package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Activity;
import cn.wolfcode.domain.Choice;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.service.IActivityItemService;
import cn.wolfcode.service.IActivityService;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IChoiceService;
import cn.wolfcode.util.PermissionAnnotation;
import cn.wolfcode.web.util.SessionUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.ResultSet;
import java.util.Date;

@Controller
@RequestMapping("/vote")
public class ActivityController {

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IActivityItemService activityItemService;

    @Autowired
    private IChoiceService choiceService;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        PageInfo<Activity> pageInfo = activityService.query(qo);
        model.addAttribute("PageInfo", pageInfo);
        return "vote/list";
    }


    @RequestMapping("/show")
    @ResponseBody
    public JsonResult delete(Choice choice, Long typeId) {
        JsonResult jsonResult = new JsonResult();
        if (choice.getActivityItemId() != null) {
            Choice check = choiceService.check(SessionUtil.getAtt(SessionUtil.USER).getId(), typeId);
            if (check == null) {
                choice.setCreateTime(new Date());
                choice.setEmployeeId(SessionUtil.getAtt(SessionUtil.USER).getId());
                choiceService.save(choice);
                int count = choiceService.getCount(typeId, choice.getActivityItemId());
                activityItemService.update(count, choice.getActivityItemId());
                return jsonResult;
            }
        }
        jsonResult.setSuccess(false);
        jsonResult.setMsg("已投票,无法再投!");
        return jsonResult;
    }


    @RequestMapping("/goResult")
    public String goResult(Long typeId, Model model) {
        model.addAttribute("result", activityItemService.getResult(typeId));
        return "vote/result";
    }


    @RequestMapping("/item")
    public String input(Long id, Model model) {
        model.addAttribute("title", activityService.getTitle(id));
        model.addAttribute("items", activityItemService.getActivityItem(id));
        return "vote/item";
    }
}
